package cn.tedu._04weibo.controller;

import cn.tedu._04weibo.base.response.JsonResult;
import cn.tedu._04weibo.base.response.StatusCode;
import cn.tedu._04weibo.mapper.UserMapper;
import cn.tedu._04weibo.pojo.dto.UserLoginParam;
import cn.tedu._04weibo.pojo.dto.UserRegParam;
import cn.tedu._04weibo.pojo.entiy.User;
import cn.tedu._04weibo.pojo.vo.UserVO;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

@Slf4j
@Tag(name = "01-用户模块")
@RestController
@RequestMapping("/v1/user/")
public class UserController {
    @Autowired
    private UserMapper userMapper;

    @PostMapping("reg")
    @Operation(summary = "用户注册")
    @ApiOperationSupport(order = 10)
    public JsonResult reg(@Validated @RequestBody UserRegParam userRegParam){
        log.debug("userRegParam = "+userRegParam);
        String username = userRegParam.getUsername();
        int i=userMapper.selectByUsername(username);
        if (i>0){//被占用
            return new JsonResult(StatusCode.USERNAME_EXISTS);
        }
        //未被占用 开始注册
        User user = new User();
        BeanUtils.copyProperties(userRegParam,user);
        user.setCreateTime(new Date());
        userMapper.insertUser(user);
        return JsonResult.ok();
    }

    @PostMapping("login")
    @Operation(summary = "用户登录")
    @ApiOperationSupport(order = 20)
    public JsonResult login(@RequestBody UserLoginParam userLoginParam, HttpSession session){
        log.debug("userLoginParam = "+userLoginParam);
        UserVO userVO=
                 userMapper.selectByUsernameAndPassword(userLoginParam);
         if (userVO!=null){//登录成功
             session.setAttribute("user",userVO);
             return JsonResult.ok(userVO);
         }
         return new JsonResult(StatusCode.USERNAME_PASSWORD_ERROR);

    }
    @GetMapping("current")
    @Operation(summary = "获取用户")
    @ApiOperationSupport(order = 30)
    public JsonResult currentUser(HttpSession session){
        UserVO userVO= (UserVO) session.getAttribute("user");
        return JsonResult.ok(userVO);
    }
    @GetMapping("logout")
    @Operation(summary = "退出登录")
    @ApiOperationSupport(order = 40)
    public void logout(HttpSession session){
        session.removeAttribute("user");
    }


}
